/**
 * Copyright 2011 Joe Choi, All rights reserved.
 */
package tec.data.persistence.jdbc;

import java.sql.SQLException;
import java.sql.Statement;

import tao.data.persistence.Query;
import tao.data.persistence.QueryResult;
import tec.data.persistence.PersistenceException;

import tao.data.structure.Iterator;
import tec.data.structure.ListControl;

/**
 * @author Joe Choi
 */
public class SqlQuery implements Query {
	public SqlQuery(Statement stm) {
		if(stm == null) throw new IllegalArgumentException("Query: Statement may not be null!");
		this.stm = stm;
		results = new ListControl<QueryResult>();
	}
	
	@Override
	public QueryResult execute(String sql) {
		QueryResult result;
		try {
			result = new JDBCQueryResult(new ResultSetAdapter(stm.executeQuery(sql)));
		} catch (SQLException e) {
			throw new PersistenceException(e);
		}
		results.add(result);
		return(result);
	}

	@Override
	public void close() {
		Iterator<QueryResult> it = results.getList().iterate();
		try {
			while(it.hasNext()) it.next().close();
			if(stm != null && (! stm.isClosed())) stm.close();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}
	}
	
	private ListControl<QueryResult> results;
	private Statement stm;
}